package com.haltakov.letterjumble.game.api;

import java.util.ArrayList;
import java.util.Iterator;

public class LetterBag {

	private ArrayList<Letter> letters; 
	private LanguageInfo languageInfo;

	public LetterBag (LanguageInfo languageInfo) {
		this(languageInfo, true);
	}

	public LetterBag(LanguageInfo languageInfo, boolean loadFormLanguage) {
		this.languageInfo = languageInfo;
		letters = new ArrayList<Letter>();
		
		if (loadFormLanguage) {
			Iterator<Letter> iter = languageInfo.letterIterator();

			while (iter.hasNext()){
				Letter l = iter.next();

				for (int i=0; i<l.getCount(); ++i)
					letters.add(l);
			}
		}		
	}

	public boolean isEmpty() {

		return letters.isEmpty();
	}

	public void addLetter(Character charachter, int count) {
		for(int i=0; i<count; i++) {
			Letter l = languageInfo.getLetter(charachter);
			letters.add(l);
		}
	}
	
	public Letter getRandomLetter() {

		if (letters.isEmpty())
			return null;

		int i = (int) (Math.random() * ((double) letters.size()));
		Letter letter = letters.get(i);
		letters.remove(i);

		return letter;
	}

	public int getLettersCount() {
		return letters.size();
	}

	public int getLetterCount(Letter l) {
		int first = letters.indexOf(l);

		if (first < 0)
			return 0;

		return letters.lastIndexOf(l) - first + 1;
	}
}